package com.deliverman.java;

import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.websocket.OnClose;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 监听 websocket 地址 /myWs
 */
@Component
@ServerEndpoint("/myWs")
@Slf4j
public class WsServerEndPoint {

    static Map<String, Session> sessions = new ConcurrentHashMap<String, Session>();

    // 连接建立时，执行的操作
    @OnOpen
    public void onOpen(Session session) {
        System.out.println("WsServerEndPoint onOpen");
        sessions.put(session.getId(), session);
        log.info("WsServerEndPoint onOpen");
    }

    // 收到客户端消息执行的操作
    @OnMessage
    public String onMessage(String message, Session session) {
        System.out.println("WsServerEndPoint onMessage: "+message);
        return "已收到";
    }

    // 连接关闭时
    @OnClose
    public void onClose(Session session) {
        log.info("WsServerEndPoint onClose, getId: "+session.getId());
        sessions.remove(session.getId());
    }

//    @Scheduled(fixedRate = 2000)
    public void sendMsg() throws IOException {
        log.info("sessions.size: "+sessions.size());
        for(String key : sessions.keySet()) {
            Session session = sessions.get(key);
            session.getBasicRemote().sendText("心跳");
        }
    }
}
